package jm.nj.demo14mian.demo02;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/*
* 发送端
* 1.创建DatagramSocket对象
* 2.创建DatagramPacket对象,并封装数据
* 3.发送数据
* 4.释放流资源
* */
public class UDPsend {
    public static void main(String[] args) throws IOException {
        //1.创建DatagramSocket对象
        DatagramSocket sendSocket = new DatagramSocket(8848);
        //创建DatagramPacket对象并封装
        //public DatagramPacket(byte[] buf ,int length ,InetAddress address,int port)
        //构造数据包,用长度length的包发送到指定主机的指定端口号

        byte[] buffer = "hello ,UDP".getBytes();
        DatagramPacket dp = new DatagramPacket(buffer, buffer.length, InetAddress.getByName("127.0.0.1"),12306);

        //发送数据
        //public void send(DatagramPacket p)从此套接字发送数据
        sendSocket.send(dp);

        System.out.println(sendSocket.getLocalPort());
        //释放流资源
        sendSocket.close();
    }

}
